import { defineStore } from 'pinia'
import { ref } from 'vue'
import { cart } from '@/model/cartModel'
import {
  searchGoodsInfoByGoodsInfoId,
  insertCartList,
  searchCartList,
  deleteCart,
  deleteCartAll
} from '@/api/cart'
export default defineStore('cart', () => {
  const cartArr = ref<cart[]>()
  const getCartByLocalStorage = async () => {
    const user_id = localStorage.getItem('userId')
    const localCartString = localStorage.getItem('cart') || 'null'
    cartArr.value = JSON.parse(localCartString)
    let once = sessionStorage.getItem('once')
    if (!once && once !== 'false') {
      sessionStorage.setItem('once', 'true')
      once = 'true'
    }
    // 如果用户登录
    if (user_id) {
      // 获取用户的购物车
      const result = await searchCartList(Number(user_id))
      if (result.status === 200 && cartArr.value && once === 'true') {
        result.data.forEach((item: any) => {
          // 用来判断当前购物车中是否有数据
          let flag = true
          // 循环购物车
          cartArr.value!.forEach((e: cart) => {
            // 如果购物车中有当前添加的数据
            if (e.goodsInfo_id === item.goodsInfo_id) {
              // 购物车数量增加
              flag = false
              e.goods_count++
            }
          })
          // 存在
          if (flag) {
            // 添加购物车
            cartArr.value!.push(item)
          }
          // 存储购物车到localStorage
          saveCartInLocalStorage()
        })
      }
      sessionStorage.setItem('once', 'false')
    }
  }
  const saveCartInLocalStorage = async () => {
    // 存储本地购物车
    cartArr.value && cartArr.value.length > 0
      ? localStorage.setItem('cart', JSON.stringify(cartArr.value))
      : localStorage.removeItem('cart')
    // 获取用户id
    const user_id = localStorage.getItem('userId')
    // 如果登录
    if (user_id && cartArr.value) {
      const cartList: any = []
      // 循环购物车
      cartArr.value.forEach((e, index) => {
        const cart = [
          e.cart_id ? e.cart_id : Number(user_id + '0' + index),
          e.goodsInfo_id,
          e.goods_count,
          e.goods_checked ? 1 : 0,
          Number(user_id)
        ]
        cartList.push(cart)
      })
      // 添加购物车到数据库
      await insertCartList(cartList)
    }
  }
  const saveGoodsInLocalStorage = (cart: cart) => {
    return new Promise<number>(async (resolve, reject) => {
      // 如果购物车存在
      if (cartArr.value) {
        // 用来判断当前购物车中是否有数据
        let flag = true
        // 循环购物车
        cartArr.value.forEach((e: cart) => {
          // 如果购物车中有当前添加的数据
          if (e.goodsInfo_id === cart.goodsInfo_id) {
            // 购物车数量增加
            flag = false
            e.goods_count++
          }
        })
        // 存在
        if (flag) {
          // 添加购物车
          cartArr.value.push(cart)
        }
        // 存储购物车到localStorage
        saveCartInLocalStorage()
      } else {
        // 如果购物车不存在
        // 将传入的数据保存到购物车
        cartArr.value = [cart]
        // 存储
        saveCartInLocalStorage()
      }
      // 如果购物车存在
      if (cartArr.value.length > 0) {
        // 成功，返回长度
        resolve(cartArr.value.length)
      } else {
        // 失败，返回0
        reject(0)
      }
    })
  }
  const goodsInfoArr = ref<any[]>()
  const getGoodsInfo = async () => {
    // 如果购物车存在
    if (cartArr.value) {
      // 数组用来存储购物车中商品的id
      const goodsInfo_ids: number[] = []
      // 循环购物车获取id
      cartArr.value.forEach(item => {
        goodsInfo_ids.push(item.goodsInfo_id)
      })
      // 发送请求获取商品的详细信息
      const result = await searchGoodsInfoByGoodsInfoId(goodsInfo_ids)
      if (result.status === 200) goodsInfoArr.value = result.data
    }
  }
  const delCart = async (goodsInfo_id: number, user_id: number) => {
    const result = await deleteCart(goodsInfo_id, user_id)
    result.status === 200 && getCartByLocalStorage()
  }
  const delCartAll = async (user_id: number) => {
    const result = await deleteCartAll(user_id)
    result.status === 200 && localStorage.removeItem('cart')
  }
  return {
    cartArr,
    getCartByLocalStorage,
    saveCartInLocalStorage,
    saveGoodsInLocalStorage,
    goodsInfoArr,
    getGoodsInfo,
    delCart,
    delCartAll
  }
})
